const path = require('path');
const _ = require('lodash');
const webpack = require('webpack');
const glob = require('glob-all');
const config = require('./dev.conf');
const utils = require('../component/utils');
const baseWebpackConfig = require('./webpack.base.conf');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');

module.exports = function ({subProjectName}) {
    const htmlFiles = glob.sync(`src/${subProjectName}/pages/*/*.html`, {
        cwd: path.resolve(__dirname, '..'),
    });
    const htmlPlugins = _.map(htmlFiles, function (filename) {
        const basename = path.basename(filename, '.html');
        const pluginConfig = {
            template: filename,
            filename: `${config.assetsRoot}/${subProjectName}/${basename}.html`,
            // 页面模板需要加对应的js脚本，如果不加这行则每个页面都会引入所有的js脚本
            chunks: ['manifest', 'vendor', basename],
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        };
        return new HtmlWebpackPlugin(pluginConfig);
    });

    const manifestFiles = glob.sync(`src/${subProjectName}/pages/*/manifests/**/*.json`, {
        cwd: path.resolve(__dirname, '..'),
    });

    const manifestPlugins = _.map(manifestFiles, function (filename) {
        const pluginConfig = {
            context: path.resolve(__dirname, '..'),
            manifest: require(path.resolve(__dirname, '..', filename)),
        };
        return new webpack.DllReferencePlugin(pluginConfig);
    });

    const baseWebpackDevConfig = baseWebpackConfig(config, {subProjectName});
    _.each(baseWebpackDevConfig.entry, function (files) {
        files.push('./component/dev-client.js');
    });

    return merge(baseWebpackDevConfig, {
        output: {
            path: path.resolve(config.assetsRoot, subProjectName),
            publicPath: `/${subProjectName}/`,
            filename: utils.assetsPath('js/[name].js', config.assetsSubDirectory),
        },
        module: {
            rules: utils.styleLoaders({sourceMap: true})
        },
        // cheap-module-eval-source-map is faster for development
        devtool: '#cheap-module-eval-source-map',
        plugins: [
            new webpack.DefinePlugin({
                'process.env': JSON.stringify(process.env.NODE_ENV)
            }),
            // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoEmitOnErrorsPlugin(),

        ].concat(manifestPlugins).concat(htmlPlugins).concat([
            new FriendlyErrorsPlugin()
        ])
    });
};
